package com.mj.transaction;

import com.mj.utils.Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 事务消息，不支持延迟消息和批量消息
 */
public class TransactionProducer {
    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        // 1.创建一个事务消息生产者，指定生产者组名
        TransactionMQProducer producer = new TransactionMQProducer(Util.ProducerGroup);
        // 2.设置NameServer的地址
        producer.setNamesrvAddr(Util.NamesrvAddr);
        // 异步提交事务状态，提升性能
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2000), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread();
                thread.setName("executor-service");
                return null;
            }
        });
        producer.setExecutorService(threadPoolExecutor);
        // 做一个本地事务监听器，来查看事务状态
        producer.setTransactionListener(new TransactionListener() {
            // 执行本地事务
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                String tags = message.getTags();
                //TagA模拟一下提交，所以很快消费者就能收到
                if (StringUtils.contains("TagA", tags)) {
                    return LocalTransactionState.COMMIT_MESSAGE;
                }

                //TagB模拟一下回滚，直接就丢弃了
                if (StringUtils.contains("TagB", tags)) {
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }

                //TagC、TagD、TagE就会不断的进行检查
                return LocalTransactionState.UNKNOW;
            }

            // 回查本地事务，最多15次
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                String tags = messageExt.getTags();
                //TagC模拟一下提交，经过一次重试之后才会发送成功，所以要等一会，比TagA慢
                if (StringUtils.contains("TagC", tags)) {
                    return LocalTransactionState.COMMIT_MESSAGE;
                }

                //TagD模拟一下回滚，检查一次之后就丢弃了
                if (StringUtils.contains("TagD", tags)) {
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }

                //TagE不断的进行检查，15次之后不再检查，提交到rocketmq中的一个内部topic：RMQ_SYS_TRANS_HALF_TOPIC，最终经过服务端的确认彻底超时之后删除掉，如果在超时之前被确认还是可以发送成功的。
                return LocalTransactionState.UNKNOW;
            }
        });
        // 3.启动生产者实例
        producer.start();
        String[] tags = new String[]{"TagA", "TagB", "TagC", "TagD", "TagE"};
        // 4.使用for循环发送10条消息
        for (int i = 0; i < 10; i++) {
            // 创建一条消息
            Message message = new Message(Util.Topic, tags[i % tags.length], (tags[i % tags.length] + "_transaction_message_" + i).getBytes(StandardCharsets.UTF_8));
            // 5.发送消息并接收发送结果
            SendResult sendResult = producer.sendMessageInTransaction(message, null);
            // 打印发送结果，包括消息ID、发送状态等信息
            System.out.println(sendResult);
            Thread.sleep(10);
        }
        // 多等待一会，用来查看回查信息
        Thread.sleep(100000);
        // 6.发送完所有消息后，关闭生产者实例，释放资源
        producer.shutdown();

    }
}
